package org.csu.newpetstoreback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.newpetstoreback.common.CommonResponse;
import org.csu.newpetstoreback.entity.Item;
import org.csu.newpetstoreback.entity.Order;
import org.csu.newpetstoreback.entity.OrderItem;
import org.csu.newpetstoreback.persistence.ItemMapper;
import org.csu.newpetstoreback.persistence.OrderItemMapper;
import org.csu.newpetstoreback.persistence.OrderMapper;
import org.csu.newpetstoreback.service.OrderService;
import org.csu.newpetstoreback.vo.ItemLittleVO;
import org.csu.newpetstoreback.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("orderService")
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private ItemMapper itemMapper;

    @Override
    public CommonResponse<List<OrderVO>> getOrders() {
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Order> orderList = orderMapper.selectList(null);
        if(orderList.isEmpty()){
            return CommonResponse.createForNotFound("没有订单信息");
        }

        for (Order order:orderList){

            QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orderId", order.getOrderId());//column的orderId是数据库表里的小写吗？
            List<OrderItem> orderItemList = orderItemMapper.selectList(queryWrapper);

            List<ItemLittleVO> itemLittleVOList = new ArrayList<>();
            for (OrderItem orderItem:orderItemList){
                ItemLittleVO itemLittleVO = orderItemToItemLittleVO(orderItem);
                itemLittleVOList.add(itemLittleVO);
            }

            OrderVO orderVO = orderToOrderVO(order, itemLittleVOList);
            orderVOList.add(orderVO);
        }

        return CommonResponse.createForSuccess(orderVOList);
    }

    @Override
    public CommonResponse<OrderVO> addOrder(OrderVO orderVO) {
        Order order = new Order();
        order.setOrderId(orderVO.getOrderId());
        order.setUsername(orderVO.getUsername());
        order.setRealname(orderVO.getRealname());
        order.setOrderDate(orderVO.getOrderDate());
        order.setOrderStatus(orderVO.getOrderStatus());
        order.setShipCountry(orderVO.getShipCountry());
        order.setShipCity(orderVO.getShipCity());
        order.setAddress(orderVO.getAddress());
        order.setCourier(orderVO.getCourier());
        order.setTotalPrice(orderVO.getTotalPrice());
        order.setPayType(orderVO.getPayType());

        int addOrderSuccess = orderMapper.insert(order);//insert插入的返回值是新增数据的ID。当然，前提是数据库支持自增的ID主键。
        int addOrderItemSuccess = -1;

        List<ItemLittleVO> itemList = orderVO.getItemList();
        //增强For循环（获取index需要定义额外的变量）
        int i = 1;
        for (ItemLittleVO itemLittleVO:itemList){
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(orderVO.getOrderId());
            orderItem.setLineNum(i);
            orderItem.setItemId(itemLittleVO.getItemId());
            orderItem.setQuantity(itemLittleVO.getQuantity());
            orderItem.setPrice(itemLittleVO.getPrice());

            addOrderItemSuccess = orderItemMapper.insert(orderItem);

            i++;
        }

        if (addOrderSuccess > 0 && addOrderItemSuccess > 0 ){
            return CommonResponse.createForSuccessMessage("订单添加成功");
        }else {
            return CommonResponse.createForUnauthorized("订单添加失败");
        }
    }

    @Override
    public CommonResponse<OrderVO> getOrderById(int orderId) {
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderId", orderId);//column的orderId是数据库表里的小写吗？
        List<OrderItem> orderItemList = orderItemMapper.selectList(queryWrapper);
        if(orderItemList.isEmpty()){
            return CommonResponse.createForNotFound("没有该订单的信息");
        }

        List<ItemLittleVO> itemLittleVOList = new ArrayList<>();
        for (OrderItem orderItem:orderItemList){
            ItemLittleVO itemLittleVO = orderItemToItemLittleVO(orderItem);
            itemLittleVOList.add(itemLittleVO);
        }

        Order order = orderMapper.selectById(orderId);

        OrderVO orderVO = orderToOrderVO(order, itemLittleVOList);

        return CommonResponse.createForSuccess(orderVO);
    }

    @Override
    public CommonResponse<OrderVO> setOrderById(int orderId, OrderVO orderVO) {

        Order order = new Order();
        order.setOrderId(orderVO.getOrderId());
        order.setUsername(orderVO.getUsername());
        order.setRealname(orderVO.getRealname());
        order.setOrderDate(orderVO.getOrderDate());
        order.setOrderStatus(orderVO.getOrderStatus());
        order.setShipCountry(orderVO.getShipCountry());
        order.setShipCity(orderVO.getShipCity());
        order.setAddress(orderVO.getAddress());
        order.setCourier(orderVO.getCourier());
        order.setTotalPrice(orderVO.getTotalPrice());
        order.setPayType(orderVO.getPayType());

        int updateOrderSuccess = orderMapper.updateById(order);

        //先把orderItem里有的item商品都删了，再插入，要不然可能item数量都不对
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderId", orderId);
        int deleteOrderItemSuccess = orderItemMapper.delete(queryWrapper);

        int updateOrderItemSuccess = -1;

        List<ItemLittleVO> itemList = orderVO.getItemList();
        //增强For循环（获取index需要定义额外的变量）
        int i = 1;
        for (ItemLittleVO itemLittleVO:itemList){
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(orderVO.getOrderId());
            orderItem.setLineNum(i);
            orderItem.setItemId(itemLittleVO.getItemId());
            orderItem.setQuantity(itemLittleVO.getQuantity());
            orderItem.setPrice(itemLittleVO.getPrice());

            updateOrderItemSuccess = orderItemMapper.insert(orderItem);

            i++;
        }

        if (updateOrderSuccess > 0 && deleteOrderItemSuccess > 0 && updateOrderItemSuccess > 0){
            return CommonResponse.createForSuccessMessage("订单更新成功");
        }else {
            return CommonResponse.createForUnauthorized("订单更新失败");
        }
    }

    @Override
    public CommonResponse<OrderVO> deleteOrderById(int orderId) {
        int deleteOrderSuccess = orderMapper.deleteById(orderId);

        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderId", orderId);
        int deleteOrderItemSuccess = orderItemMapper.delete(queryWrapper);

        if(deleteOrderSuccess > 0 && deleteOrderItemSuccess > 0){
            return CommonResponse.createForSuccessMessage("订单删除成功");

        }else {
            return CommonResponse.createForNotFound("没有该订单的信息，无法删除");
        }
    }

    @Override
    public CommonResponse<OrderVO> cancelOrderById(int orderId) {
        Order order = orderMapper.selectById(orderId);
        order.setOrderStatus("YT");//状态改为“已退货”

        int cancelOrderSuccess = orderMapper.updateById(order);

        if(cancelOrderSuccess > 0){
            return CommonResponse.createForSuccessMessage("退货成功");

        }else {
            return CommonResponse.createForNotFound("退货失败");
        }
    }

    @Override
    public CommonResponse<OrderVO> receiveOrderById(int orderId) {
        Order order = orderMapper.selectById(orderId);
        order.setOrderStatus("YS");//状态改为“已收货”

        int receiveOrderSuccess = orderMapper.updateById(order);

        if(receiveOrderSuccess > 0){
            return CommonResponse.createForSuccessMessage("收货成功");

        }else {
            return CommonResponse.createForNotFound("收货失败");
        }
    }

    @Override
    public int getOrderNum() {

        Order orderMax = orderMapper.selectOne(new QueryWrapper<Order>().orderByDesc("orderId").last("limit 1"));

        int orderNum = orderMax.getOrderId();

        return orderNum;
    }

    private ItemLittleVO orderItemToItemLittleVO(OrderItem orderItem){
        ItemLittleVO itemLittleVO = new ItemLittleVO();

        Item item = itemMapper.selectById(orderItem.getItemId());

        itemLittleVO.setItemId(orderItem.getItemId());
        itemLittleVO.setQuantity(orderItem.getQuantity());
        itemLittleVO.setPrice(orderItem.getPrice());
        itemLittleVO.setIName(item.getIName());
        itemLittleVO.setIImage(item.getIImage());
        itemLittleVO.setIDescn(item.getIDescn());

        return itemLittleVO;
    }

    private OrderVO orderToOrderVO(Order order, List<ItemLittleVO> itemLittleVOList){
        OrderVO orderVO = new OrderVO();

        orderVO.setOrderId(order.getOrderId());
        orderVO.setUsername(order.getUsername());
        orderVO.setRealname(order.getRealname());
        orderVO.setOrderDate(order.getOrderDate());
        orderVO.setOrderStatus(order.getOrderStatus());
        orderVO.setShipCountry(order.getShipCountry());
        orderVO.setShipCity(order.getShipCity());
        orderVO.setAddress(order.getAddress());
        orderVO.setCourier(order.getCourier());
        orderVO.setTotalPrice(order.getTotalPrice());
        orderVO.setPayType(order.getPayType());

        orderVO.setItemList(itemLittleVOList);

        return orderVO;
    }
}
